package com.wld.blacklist.common.exception;

import com.wld.blacklist.common.enums.CodeEnum;
import com.wld.blacklist.dao.result.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常拦截处理类
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 入参参数有问题
     * @param ex MethodArgumentNotValidException.class
     * @return ResultVo
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVo methodArgumentNotValidException(MethodArgumentNotValidException ex){
        log.error("入参参数无效异常");
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder(bindingResult.getFieldErrors().size()*16);

        for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
            FieldError fieldError = bindingResult.getFieldErrors().get(i);
            sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage());
        }
        return ResultVo.failed(CodeEnum.PARAM_ERROR,sb.toString());
    }

    /**
     * 业务流程异常
     */
    @ExceptionHandler(BusinessExceptions.class)
    @ResponseBody
    public ResultVo businessExceptions(BusinessExceptions ex) {
        log.error("业务发生异常："+ex.getMessage());
        return ResultVo.failed(CodeEnum.BUSINESS_ERROR,ex.getMessage());
    }
}
